<?php


namespace App\Http\Api\Controllers;

use App\Library\JsonData;
use App\Models\CoAreas;
use App\Models\CoSchool;
use App\Models\CoSchoolBuilding;
use App\Models\CoSchoolName;
use App\Models\CoUser;
use App\Models\CoUserAddress;
use App\Models\CoUserCity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class UserCttyController extends Controller
{
    public function __construct(Request $request)
    {
        // 调用父类前置方法
        parent::__construct();
        $this->api_token = trim($request->header('token'));
        $this->get_user();
        if(empty($this->user_info)){
            return JsonData::error('未登录','',601);
        }
        if($this->user_info->type !=1){
            return JsonData::error('用户禁止登录','',601);
        }
    }

    /**
     * 地址列表
     */
    public function data_list(){
        try {
            $data = CoUserCity::where('co_user_city.user_id',$this->user_info->id)
                ->join('co_school','co_school.id','=','co_user_city.school_id')
                ->join('co_school_building','co_school_building.id','=','co_user_city.school_building_id')
                ->select('co_user_city.*','co_school.name as school_name','co_school_building.title as building_name')
                ->orderBy('is_default','desc')
                ->paginate(10);
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }


    /**
     * 添加用户收件或取件地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUser(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'school_building_id' => 'required|integer',
                'school_id'=>'required|integer',
                'name' => 'required',
                'tel'=>'required',
                'sex'=>'required|integer',
                'address'=>'required',
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
            //赋值
            $school_building_id=$request->school_building_id;
            $school_id=$request->school_id;
            $name=$request->name;
            $tel=$request->tel;
            $sex=$request->sex;
            $address=$request->address;
            if (!preg_match("/^1[345789]\d{9}$/", $tel)) {
                return JsonData::error( "手机号格式不正确",'',500);
            }
            //查询
            $school_info=CoSchool::where("id",$school_id)->where('status',1)->first();
            if(empty($school_info)){
                return JsonData::error('学校不存在','',500);
            }
            $school_name_info=CoSchoolBuilding::where("id",$school_building_id)->where('status',1)->first();
            if(empty($school_name_info)){
                return JsonData::error('楼栋不存在','',500);
            }
            //添加地址
            $CoUserCity = new CoUserCity();
            $CoUserCity->school_building_id = $school_building_id;
            $CoUserCity->school_id = $school_id;
            $CoUserCity->user_id = $this->user_info->id;
            $CoUserCity->name = $name;
            $CoUserCity->tel = $tel;
            $CoUserCity->sex = $sex;
            $CoUserCity->address = $address;
            if($CoUserCity->where('user_id',$this->user_info->id)->count('id') <= 0){
                $CoUserCity->is_default = 1;
            }
            $res =  $CoUserCity->save();
            if($res){
                return JsonData::success('添加成功','',200);
            }else{
                return JsonData::success('添加失败','',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }

    /**
     * 修改地址
     * @param Request $request
     */
    public function editUser(Request $request){
        try {
            //赋值
            $id=intval($request->get('id'));
            if(empty($id)){
                return JsonData::error('参数错误','',500);
            }
            $CoUserCity = CoUserCity::where('id',$id)->where('user_id',$this->user_info->id)->first();
            if(empty($CoUserCity)){
                return JsonData::error('地址不存在','',500);
            }

            $school_id=$request->get('school_id');
            if($school_id){
                $school_info=CoSchool::where("id",$school_id)->where('status',1)->first();
                if(empty($school_info)){
                    return JsonData::error('学校不存在','',500);
                }
                $CoUserCity->school_id = $school_id;
            }
            $school_building_id=$request->get('school_building_id');
            if($school_building_id){
                $school_name_info=CoSchoolBuilding::where("id",$school_building_id)->where('status',1)->first();
                if(empty($school_name_info)){
                    return JsonData::error('楼栋不存在','',500);
                }
                $CoUserCity->school_building_id = $school_building_id;
            }
            $name=trim($request->get('name'));
            if(!empty($name)){
                $CoUserCity->name = $name;
            }
            $sex=intval($request->get('sex'));
            if(in_array($sex,[1,2])){
                $CoUserCity->sex = $sex;
            }
            $tel=trim($request->get('tel'));
            if(!empty($tel) ){
                if (!preg_match("/^1[345789]\d{9}$/", $tel)) {
                    return JsonData::error( "手机号格式不正确",'',500);
                }
                $CoUserCity->tel = $tel;
            }
            $address=trim($request->get('address'));
            if(!empty($address)){
                $CoUserCity->address = $address;
            }
            DB::beginTransaction();
            $is_default=intval($request->get('is_default'));
            if($is_default){
                if($CoUserCity->is_default ==1){
                    $CoUserCity->is_default =0;
                }else {
                    $num = CoUserCity::where('user_id',$this->user_info->id)->where('is_default',0)->count();
                    if($num > 0){
                        $res = CoUserCity::where('user_id',$this->user_info->id)->update(['is_default'=>0]);
                        if(!$res){
                            DB::rollBack();
                            return JsonData::success('修改失败','',500);
                        }
                    }
                    $CoUserCity->is_default =1;
                }
            }
            $res =  $CoUserCity->save();
            if($res){
                DB::commit();
                return JsonData::success('修改成功','',200);
            }else{
                DB::rollBack();
                return JsonData::success('修改失败','',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }
    }


    /**
     * 删除地址
     * @param Request $request
     */
    public function userDetails(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer',
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
            //赋值
            $id=$request->id;
            //查询
            $data = CoUserCity::where('co_user_city.user_id',$this->user_info->id)
                ->where('co_user_city.id',$id)
                ->join('co_school','co_school.id','=','co_user_city.school_id')
                ->join('co_school_building','co_school_building.id','=','co_user_city.school_building_id')
                ->select('co_user_city.*','co_school.name as school_name','co_school_building.title as building_name','co_school_building.school_name_id')
                ->first();
            if(empty($data)){
                return JsonData::error('地址不存在','',500);
            }
            return JsonData::success('返回成功',$data,200);

        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }
    }

    /**
     * 地址详情
     * @param Request $request
     */
    public function delUser(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer',
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
            //赋值
            $id=$request->id;
            //查询
            $CoUserCity = CoUserCity::where('id',$id)->where('user_id',$this->user_info->id)->first();
            if(empty($CoUserCity)){
                return JsonData::error('地址不存在','',500);
            }
            $res = $CoUserCity->delete();
            if($res){
                return JsonData::success('删除成功','',200);
            }else{
                return JsonData::success('删除失败','',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }
    }


    /***
     * 联系人地址信息
     * @param Request $request
     */
    public function address_list(Request $request){
        try {
            $data = CoUserAddress::where('user_id',$this->user_info->id)
//                ->join('co_areas','co_areas.id','=','co_user_address.county')
//                ->select('co_user_address.*','co_areas.mergename')
                ->orderBy('is_default','desc')
                ->paginate(10);
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }


    /**
     * 添加用户联系人地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addaddress(Request $request){
        $validator = Validator::make($request->all(), [
            'province' => 'required|integer',
            'city'=>'required|integer',
            'county'=>'required|integer',
            'name' => 'required',
            'tel'=>'required',
            'address'=>'required',
            'county_name'=>'required',
        ]);
        if ($validator->fails()) {
            return JsonData::error('参数错误','',500);
        }
        //赋值
        $province=$request->province;
        $city=$request->city;
        $county=$request->county;
        $tel=$request->tel;
        if (!preg_match("/^1[345789]\d{9}$/", $tel)) {
            return JsonData::error( "手机号格式不正确",'',500);
        }
        $name=$request->name;
        $address=$request->address;
        $county_name =$request->county_name;
//        //查询
//        $province_id=CoAreas::where("id",$province)->value('id');
//        if(empty($province_id)){
//            return JsonData::error('省不存在','',500);
//        }
//        $city_id=CoAreas::where("id",$city)->value('id');
//        if(empty($city_id)){
//            return JsonData::error('市不存在','',500);
//        }
//        $county_id=CoAreas::where("id",$county)->value('id');
//        if(empty($county_id)){
//            return JsonData::error('区县不存在','',500);
//        }
        //添加地址
        $CoUserAddress = new CoUserAddress();
        $CoUserAddress->province = $province;
        $CoUserAddress->city = $city;
        $CoUserAddress->county = $county;
        $CoUserAddress->user_id = $this->user_info->id;
        $CoUserAddress->name = $name;
        $CoUserAddress->tel = $tel;
        $CoUserAddress->address = $address;
        $CoUserAddress->county_name = $county_name;
        if($CoUserAddress->where('user_id',$this->user_info->id)->count('id') <= 0){
            $CoUserAddress->is_default = 1;
        }
        $res =  $CoUserAddress->save();
        if($res){
            return JsonData::success('添加成功','',200);
        }else{
            return JsonData::success('添加失败','',500);
        }
    }

    /**
     * 修改联系人地址
     * @param Request $request
     */
    public function editaddress(Request $request){
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return JsonData::error('参数错误','',500);
        }
        //赋值
        $id=$request->id;
        $CoUserAddress = CoUserAddress::where('id',$id)->where('user_id',$this->user_info->id)->first();
        if(empty($CoUserAddress)){
            return JsonData::error('地址不存在','',500);
        }
        $province=intval($request->get('province'));
        if($province){
//            $province_id=CoAreas::where("id",$province)->value('id');
//            if(empty($province_id)){
//                return JsonData::error('省不存在','',500);
//            }
            $CoUserAddress->province = $province;
        }
        $city=intval($request->get('city'));
        if($city){
//            $city_id=CoAreas::where("id",$city)->value('id');
//            if(empty($city_id)){
//                return JsonData::error('市不存在','',500);
//            }
            $CoUserAddress->city = $city;
        }
        $county=intval($request->get('county'));
        if($county){
//            $county_id=CoAreas::where("id",$county)->value('id');
//            if(empty($county_id)){
//                return JsonData::error('区县不存在','',500);
//            }
            $CoUserAddress->city = $city;
        }
        $county_name=trim($request->get('county_name'));
        if($county){
            $CoUserAddress->county_name = $county_name;
        }
        $tel=$request->get('tel');
        if(!empty($tel) ){
            if (!preg_match("/^1[345789]\d{9}$/", $tel)) {
                return JsonData::error( "手机号格式不正确",'',500);
            }
            $CoUserAddress->tel = $tel;
        }
        $address=trim($request->get('address'));
        if(!empty($address)){
            $CoUserAddress->address = $address;
        }
        DB::beginTransaction();
        $is_default=$request->get('is_default');
        if($is_default){
            if($CoUserAddress->is_default ==1){
                $CoUserAddress->is_default =0;
            }else{
                $num = CoUserAddress::where('user_id',$this->user_info->id)->where('is_default',1)->count();
                if($num >0) {
                    $res = CoUserAddress::where('user_id', $this->user_info->id)->update(['is_default' => 0]);
                    if (!$res) {
                        DB::rollBack();
                        return JsonData::success('修改失败', '', 500);
                    }
                }
                $CoUserAddress->is_default =1;
            }
        }
        $res =  $CoUserAddress->save();
        if($res){
            DB::commit();
            return JsonData::success('修改成功','',200);
        }else{
            DB::rollBack();
            return JsonData::success('修改失败','',500);
        }
    }


    /**
     * 删除联系人地址
     * @param Request $request
     */
    public function deladdress(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer',
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
            //赋值
            $id=$request->id;
            //查询
            $CoUserAddress = CoUserAddress::where('id',$id)->where('user_id',$this->user_info->id)->first();
            if(empty($CoUserAddress)){
                return JsonData::error('地址不存在','',500);
            }
            $res = $CoUserAddress->delete();
            if($res){
                return JsonData::success('删除成功','',200);
            }else{
                return JsonData::success('删除失败','',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }
    }

    /**
     * 联系人详情
     * @param Request $request
     */
    public function detailsaddress(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required|integer',
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
            //赋值
            $id=$request->id;
            //查询
            $data = CoUserAddress::where('user_id',$this->user_info->id)
                ->where('id',$id)
//                ->join('co_areas','co_areas.id','=','co_user_address.county')
//                ->select('co_user_address.*','co_areas.mergename')
                ->first();
            if(empty($data)){
                return JsonData::error('地址不存在','',500);
            }
            return JsonData::success('返回成功',$data,200);

        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }
    }

}
